package org.boticelli.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class DateUtil
{
    private DateUtil()
    {

    }

    public static int daySinceEpoch(Calendar cal)
    {
        return (int)(cal.getTime().getTime()/DateUtil.MILLISECONDS_PER_DAY)+1;
    }

    public static Calendar fromDaySinceEpoch(int day)
    {
        Calendar cal=Calendar.getInstance();
        zeroTimeFields(cal);
        cal.set(Calendar.YEAR, 1970);
        cal.set(Calendar.MONTH, 0);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.add(Calendar.DAY_OF_MONTH, day);
        return cal;
    }

    public static final long MILLISECONDS_PER_DAY = 1000*60*60*24;


    private final static Pattern DAY_PATTERN=Pattern.compile("([0-2][0-9]{3})(0[1-9]|1[0-2])(0[1-9]|1[0-9]|2[0-9]|3[01])");

    /**
     * Returns a Calendar object for the given day string at
     * 00:00:00.000. If day is <code>null</code>, the current
     * date is used
     *
     * @param day
     * @return
     */
    public static Calendar getCalendarFor(String day)
    {
        Calendar today = Calendar.getInstance();
        zeroTimeFields(today);
        if (day != null)
        {
            Matcher matcher = DAY_PATTERN.matcher(day);
            if (!matcher.matches())
            {
                throw new IllegalArgumentException(day+" is no valid yyyymmdd date.");
            }
            today.set(Calendar.YEAR,  Integer.parseInt(matcher.group(1)));
            today.set(Calendar.MONTH, Integer.parseInt(matcher.group(2)) - 1);
            today.set(Calendar.DATE, Integer.parseInt(matcher.group(3)));
        }
        return today;
    }

    public static String toYYYYMMDD(Calendar cal)
    {
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMdd");
        return dateFormat.format(cal.getTime());
    }

    public static String toYYYYMMDD(Date date)
    {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return toYYYYMMDD(cal);
    }

    public static String daySinceEpochToYYYYMMDD(int day)
    {
        return toYYYYMMDD(fromDaySinceEpoch(day));
    }

    public static void zeroTimeFields(Calendar cal)
    {
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
    }
}
